<template>
    <div>
        <el-form :model="form" style="width: 300px">
            <el-form-item>
                <el-input type="text" placeholder='名称' v-model="form.name" />
            </el-form-item>
            <el-form-item>
                <el-upload action="#" :limit="1" list-type="picture-card" :on-preview="handlePictureCardPreview"
                    :on-remove="handleRemove" :on-exceed="handleExceed" :before-upload="handleUpload"
                    :http-request="uploadAction">
                    <el-icon>
                        <Plus />
                    </el-icon>
                </el-upload>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="add">添加</el-button>
            </el-form-item>
        </el-form>
        <el-dialog v-model="dialogVisible">
            <img w-full :src="dialogImageUrl" alt="Preview Image" />
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { Plus } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import type { UploadProps, UploadRequestOptions, UploadRawFile } from 'element-plus'
import { addBannerList } from "../../api/api";
import { useRouter } from 'vue-router';

const form = reactive({
    name: '',
    img: ''
})

const dialogImageUrl = ref<string | undefined>('')
const dialogVisible = ref(false)

const handleRemove: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
    console.log(uploadFile, uploadFiles)
}

const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
    dialogImageUrl.value = uploadFile.url
    dialogVisible.value = true
}

const handleExceed: UploadProps['onExceed'] = (files) => {
    ElMessage.warning(
        `允许上传图片的最大数量为 ${files.length} 张`
    )
}

const handleUpload = (rawFile: UploadRawFile) => {
    const type = ['image/jpeg', 'image/jpg', 'image/png']
    if (type.indexOf(rawFile.type) === -1) {
        ElMessage.error('上传的文件必须是JPG、JPEG、PNG三种之一!')
        return false
    } else if (rawFile.size / 1024 / 1024 > 2) {
        ElMessage.error('图片大小不能超过2MB!')
        return false
    }
    return true
}

const uploadAction = (data: UploadRequestOptions) => {
    let reader = new FileReader() // 创建文件读取对象
    let file = data.file
    reader.readAsDataURL(file) // 文件读取转换为base64类型
    reader.onloadend = function (e: any | null) {
        // console.log(e.target.result);
        form.img = e.target.result
    }
    let param = new FormData();
    param.append('file', data.file);
}

const router = useRouter()
const add = async () => {
    let data = {
        name: form.name,
        img: form.img
    }
    if(data.name === '' && data.img === '') {
        ElMessage({
            message: '请先完成表单输入',
            type: 'error',
        })
        return
    }
    await addBannerList(data)
    router.push('/bannerlist')
}
</script>

<style scoped>

</style>